/**
 * 
 */
package ink.zhaohui.book.dao.impl.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;
import ink.zhaohui.book.bo.BookBO;
import ink.zhaohui.book.dao.IBookDAO;
import ink.zhaohui.book.vo.Page;

/**
 * @author ccc
 *
 */
@Component
public class BookDao implements IBookDAO {
	private JdbcTemplate jdbcTemplate;

	@Autowired
	public BookDao(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public BookBO queryOne(String uuid, String orderUuid) {
		// TODO Auto-generated method stub
		final String u;
		StringBuilder sql = new StringBuilder("select id,uuid,order_uuid,name,price,number,state from book where ");
		if (uuid != null) {
			u = uuid;
			sql.append("uuid=?");
		} else if (orderUuid != null) {
			u = orderUuid;
			sql.append("order_uuid=?");
		} else {
			throw new RuntimeException("uuid和orderUuid不允许同时为空");
		}
		return jdbcTemplate.queryForObject(sql.toString(), new Object[] { u }, new RowMapper<BookBO>() {

			@Override
			public BookBO mapRow(ResultSet rs, int rowNum) throws SQLException {
				// TODO Auto-generated method stub
				BookBO bo = new BookBO();
				//
				bo.setId(rs.getInt("id"));
				bo.setUuid(rs.getString("uuid"));
				bo.setOrderUuid(rs.getString("order_uuid"));
				bo.setName(rs.getString("name"));
				bo.setPrice(rs.getFloat("price"));
				bo.setNumber(rs.getInt("number"));
				bo.setStateCode(rs.getInt("state"));
				//
				return bo;
			}
		});
	}

	@Override
	public Page<BookBO> queryMore(final String name, final int pageSize, final int at) {
		// TODO Auto-generated method stub
		Page<BookBO> p = new Page();
		p.atPage = at;
		p.pageSize = pageSize;
		int n = jdbcTemplate.queryForObject("select count(*) from book where name like ?", Integer.class,
				new Object[] { name });
		p.totalPage = n / pageSize;
		if (n % pageSize > 0 && n != 0) {
			p.totalPage += 1;
		}
		List<BookBO> l;
		if (n == 0 || at > p.totalPage) {
			l = new ArrayList();
		} else {
			l = jdbcTemplate.query(
					"select id,uuid,order_uuid,name,price,number,state from book where name like ? order by id limit ?,?",
					new RowMapper<BookBO>() {

						@Override
						public BookBO mapRow(ResultSet rs, int rowNum) throws SQLException {
							// TODO Auto-generated method stub
							BookBO bo = new BookBO();
							//
							bo.setId(rs.getInt("id"));
							bo.setUuid(rs.getString("uuid"));
							bo.setOrderUuid(rs.getString("order_uuid"));
							bo.setName(rs.getString("name"));
							bo.setPrice(rs.getFloat("price"));
							bo.setNumber(rs.getInt("number"));
							bo.setStateCode(rs.getInt("state"));
							//
							return bo;
						}
					}, new Object[] { name, pageSize * (at - 1), pageSize });
		}
		p.data = l;
		return p;
	}

	@Override
	public BookBO create(final BookBO bookBO) {
		// TODO Auto-generated method stub
		KeyHolder keyHolder = new GeneratedKeyHolder();
		int n = jdbcTemplate.update(new PreparedStatementCreator() {

			@Override
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
				// TODO Auto-generated method stub
				PreparedStatement ps = con.prepareStatement(
						"insert into book(uuid,order_uuid,name,price,number,state) values(?,?,?,?,?,?)",
						Statement.RETURN_GENERATED_KEYS);
				//
				ps.setString(1, bookBO.getUuid());
				ps.setString(2, bookBO.getOrderUuid());
				ps.setString(3, bookBO.getName());
				ps.setFloat(4, bookBO.getPrice());
				ps.setInt(5, bookBO.getNumber());
				ps.setInt(6, bookBO.getStateCode());
				//
				return ps;
			}
		}, keyHolder);
		bookBO.setId(keyHolder.getKey().intValue());
		return bookBO;
	}

	@Override
	public int updateByUuid(BookBO bookBO) {
		// TODO Auto-generated method stub
		int n = -1;// not exe
		List al = new ArrayList();
		StringBuilder sql = new StringBuilder("update book set ");
		if (bookBO.getName() != null) {
			sql.append("name=?,");
			al.add(bookBO.getName());
		}
		if (bookBO.getPrice() != null) {
			sql.append("price=?,");
			al.add(bookBO.getPrice());
		}
		if (bookBO.getNumber() != null) {
			sql.append("number=?,");
			al.add(bookBO.getNumber());
		}
		if (bookBO.getStateCode()!= null) {
			sql.append("state=?,");
			al.add(bookBO.getStateCode());
		}
		if (sql.lastIndexOf(",") == sql.length() - 1) {
			sql.deleteCharAt(sql.length() - 1);
			sql.append(" where uuid=?");
			al.add(bookBO.getUuid());
			n = jdbcTemplate.update(sql.toString(), al.toArray());
		}
		return n;
	}

}
